#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2020/3/5 下午4:09
# @Author  : fugang_le
# @Software: PyCharm

import hashlib
import uuid
import time
import json
import asyncio
import random
from aiohttp import ClientSession
from hashlib import md5
import urllib.parse
import functools
from logger import logger
# formatter = logger.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")

'''使用百度和有道翻译进行回译'''


def truncate(q):
    '''截断'''
    if q is None:
        return None
    size = len(q)
    return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]


def encrypt(signStr):
    '''加密'''
    hash_algorithm = hashlib.sha256()
    hash_algorithm.update(signStr.encode('utf-8'))
    return hash_algorithm.hexdigest()

def analy_corontine_result(text):
    coron_result = text[0]
    result = set()
    for item in coron_result:
        if item._result:
            result.add(item._result)
    return list(result)


def spend_time(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        logger.info(func.__name__ + " speed time: {}".format(str(time.time() - start_time)))
        return result

    return wrapper


async def requse_get(url):
    async with ClientSession() as session:
        async with session.get(url) as response:
            try:
                response = await response.read()
                response = json.loads(response.decode('utf-8'))
                return response
            except:
                return {}



def get_baidu_translate_url(text, from_lang, to_lang):
    random.seed(2019)
    url = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
    appid = '20190821000328449'  # baiduappid
    secretKey = 'FuSNN2rDGfKHqGl2uOX2'  # baidu密钥
    salt = random.randint(32768, 65536)
    sign = appid + text + str(salt) + secretKey
    m1 = md5()
    m1.update(sign.encode())
    sign = m1.hexdigest()
    url = url + '?appid=' + appid + '&q=' + urllib.parse.quote(
        text) + '&from=' + from_lang + '&to=' + to_lang + '&salt=' + str(salt) + '&sign=' + sign
    return url


async def get_baidu_translate(text, from_lang, to_lang):
    # 顺方向译
    url = get_baidu_translate_url(text, from_lang, to_lang)
    result = await requse_get(url)
    if not result.get('trans_result'):
        logger.info("Error: {}".format(str(result)))
        return
    dst = result['trans_result'][0]['dst']

    # 反方向译回
    back_url = get_baidu_translate_url(dst, to_lang, from_lang)
    result = await requse_get(back_url)
    if not result.get('trans_result'):
        logger.info("Error: {}".format(str(result)))
        return
    dst = result['trans_result'][0]['dst']
    return dst


@spend_time
def baidu_coroutine_back_translation(text):
    from_lang = 'zh'
    language_table = ['en', 'fra', 'ru', 'de', 'est', 'pt', 'ara', 'jp', 'kor', 'vie', 'yue', 'wyw', 'spa',
                             'th', 'it', 'el', 'nl', 'pl', 'bul', 'dan', 'fin', 'cs', 'rom', 'slo', 'swe', 'hu',
                             'cht']  # 28种
    loop = asyncio.get_event_loop()
    tasks = [get_baidu_translate(text, from_lang, lang) for lang in language_table]
    result = loop.run_until_complete(asyncio.wait(tasks))
    # loop.close()
    result = analy_corontine_result(result)
    return result


def get_youdao_translate_url(text, from_lang, to_lang):
    url = 'http://openapi.youdao.com/api'
    APP_KEY = '4d860d8da93020bb'
    APP_SECRET = 'OUGZZ2hQ17kd720u9hB9fq7UzpMGFf5S'

    curtime = str(int(time.time()))
    salt = str(uuid.uuid1())
    signStr = APP_KEY + truncate(text) + salt + curtime + APP_SECRET
    sign = encrypt(signStr)

    url = url + "?q=" + text + "&from=" + from_lang + "&to=" + to_lang + "&appKey=" + APP_KEY + "&salt=" + salt + \
          "&sign=" + sign + "&signType=" + 'v3' + "&curtime=" + curtime
    return url


async def get_youdao_translate(text, from_lang, to_lang):
    # 顺方向译
    url = get_youdao_translate_url(text, from_lang, to_lang)
    result = await requse_get(url)
    if not result.get('translation'):
        logger.info("Error: {}".format(str(result)))
        return
    dst = result['translation'][0]

    # 反方向译回
    url = get_youdao_translate_url(dst, to_lang, from_lang)
    result = await requse_get(url)
    if not result.get('translation'):
        logger.info("Error: {}".format(str(result)))
        return
    dst = result['translation'][0]
    return dst


@spend_time
def youdao_coroutine_back_translation(text):
    from_lang = 'zh-CHS'
    language_table = ['en', 'yue', 'wyw', 'jp', 'kor', 'fra', 'spa', 'ru', 'pt', 'de', 'id', 'it']  # 12种
    loop = asyncio.get_event_loop()
    tasks = [get_youdao_translate(text, from_lang, lang) for lang in language_table]
    result = loop.run_until_complete(asyncio.wait(tasks))
    # loop.close()
    result = analy_corontine_result(result)
    return result

@spend_time
def coroutine_back_translation(text):
    youdao_result = youdao_coroutine_back_translation(text)
    youdao_result = youdao_result if youdao_result else []
    baidu_result = baidu_coroutine_back_translation(text)
    baidu_result = baidu_result if baidu_result else []
    conbine_result = youdao_result + baidu_result
    return list(set(conbine_result))


if __name__ == '__main__':
    text = '吃饭'
    # result = baidu_coroutine_back_translation(text)
    # result = youdao_coroutine_back_translation(text)
    result = coroutine_back_translation(text)
    print(result)
